package org.btik.lightdev.dev.udp;

import org.btik.light.meta.Dev;
import org.btik.light.meta.base.Command;
import org.btik.light.meta.base.Report;
import org.btik.light.meta.exception.LightException;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author lustre
 * @since 2023/9/24 15:10
 */
public class UdpDev implements Dev {
    private final String sn;

    InetAddress address;

    int port;

    private final DatagramSocket serverSocket;


    @Override
    public long getTimeOut() {
        return 0;
    }

    @Override
    public void sendCmdOrMsg(Command msg) {
        try {
            byte[] encode = msg.encode();
            DatagramPacket datagramPacket = new DatagramPacket(encode, encode.length);
            datagramPacket.setPort(port);
            datagramPacket.setAddress(address);
            serverSocket.send(datagramPacket);
        } catch (IOException e) {
            throw new LightException(e);
        }

    }

    @Override
    public Report sendSyncCmd(Command cmd, long timeout) {
        return null;
    }

    @Override
    public boolean isOnline() {
        return true;
    }

    public UdpDev(String sn, InetAddress address, int port, DatagramSocket serverSocket) {
        this.sn = sn;
        this.port = port;
        this.address = address;
        this.serverSocket = serverSocket;
    }

    @Override
    public String toString() {
        return "UdpDev{" +
                "sn='" + sn + '\'' +
                ", address=" + address +
                ", port=" + port +
                '}';
    }

    public void updateAddr(InetAddress address, int port) {
        this.address = address;
        this.port = port;
    }
}
